<script lang="ts" setup>
import { ref, reactive, watch } from "vue"
import { type FormInstance, type FormRules, ElMessage, ElMessageBox } from "element-plus"
import { createDyDataApi, deleteDyDataApi, updateDyDataApi, getDyDataApi, offspush } from "@/api/capture-dy/index"
import { usePagination } from "@/hooks/usePagination"
import { Search, Refresh } from "@element-plus/icons-vue"

const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
defineOptions({
  name: "SettingDy"
})
const dialogVisible = ref(false)
const settingId = ref(false)
const tableData = ref()

// #region 渲染和查数据
const searchData = reactive({
  shopId: "",
  shopName: "",
  userId: ""
})
const searchFormRef = ref<FormInstance | null>(null)
const tabledataApi = () => {
  getDyDataApi({
    shopId: searchData.shopId || "",
    shopName: searchData.shopName || "",
    userId: searchData.userId || "",
    page: paginationData.currentPage,
    size: paginationData.pageSize
  }).then((res: any) => {
    tableData.value = res.data.list
    paginationData.total = res.data.total
  })
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    tabledataApi()
  }
  paginationData.currentPage = 1
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    tabledataApi()
  }
  paginationData.currentPage = 1
}
/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], tabledataApi, { immediate: true })
// #endregion

// #region 新增和修改
const settingApi = (row: any) => {
  dialogVisible.value = true
  console.log(row, "设置")
}
const settingIdApi = (row: any) => {
  dialogVisible.value = true
  settingId.value = true
  formData.data = row
}
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确认删除店铺${row.shopName}？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteDyDataApi(row.id).then(() => {
      ElMessage.success("删除成功")
      tabledataApi()
    })
  })
}
const settingtable = async () => {
  if (settingId.value == false) {
    dialogVisible.value = false
    await createDyDataApi(formData.data).then((res: any) => {
      if (res.code) {
        ElMessage.success(res.data)
        tabledataApi()
      }
    })
  } else {
    dialogVisible.value = false
    await updateDyDataApi(formData.data).then((res: any) => {
      ElMessage.success(res.data)
      tabledataApi()
    })
  }
}
// #endregion

// #region 所有团队
import { useTeamStore } from "@/store/modules/team"
const teamStore = useTeamStore()
const tableDataB = ref<any[]>([])
teamStore.getTeamFn()
watch(
  [() => teamStore.teamListStore],
  (newValue) => {
    tableDataB.value = newValue.flat()
  },
  { immediate: true }
)

// #endregion

// #region 弹出框
const formData = reactive<any>({ data: {} })
const formRef = ref<FormInstance | null>(null)
const formRules: FormRules = reactive({
  shopId: [{ required: true, trigger: "blur", message: "请输入店铺ID" }],
  shopName: [{ required: true, trigger: "blur", message: "请输入店铺名字" }],
  index: [{ required: true, trigger: "blur", message: "请输入店铺索引" }],
  userId: [{ required: true, trigger: "blur", message: "请选择授权账户" }]
})
const clearValidate = () => {
  formRef.value?.clearValidate()
}
const resetForm = () => {
  formData.data = {}
  settingId.value = false
  clearValidate()
}
const handleCreate = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      settingtable()
    } else {
      return false
    }
  })
}
// #endregion
const shopIds = ref<any>([
  {
    id: 0,
    name: "云邮平台"
  },
  {
    id: 1,
    name: "火影平台"
  },
  {
    id: 2,
    name: "河南电信抖店"
  },
  {
    id: 3,
    name: "追创科技通信"
  },
  {
    id: 4,
    name: "惠弘流量企业店"
  },
  {
    id: 5,
    name: "追创科技流量企业店"
  }
])

const handleStatusChange = (row: any) => {
  // console.log(row, "开关")
  offspush({ id: row.id, offs: row.offs }).then((res: any) => {
    if (res.code == 200) {
      tabledataApi()
    }
  })
}
</script>
<template>
  <div class="app-container">
    <el-card shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item label="系统账号" prop="userId">
          <el-select v-model="searchData.userId" filterable clearable style="width: 240px">
            <el-option v-for="item in tableDataB" :key="item.name" :label="item.nickName" :value="item.id"
          /></el-select>
        </el-form-item>
        <el-form-item prop="shopId" label="抖音店铺ID">
          <el-input v-model.trim="searchData.shopId" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="shopName" label="抖音店铺名称">
          <el-input v-model.trim="searchData.shopName" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" @click="settingApi">店铺配置</el-button>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData">
          <el-table-column prop="id" label="ID" width="120" align="center" />
          <el-table-column prop="shopId" label="抖音店铺ID" align="center" />
          <el-table-column prop="shopName" label="抖音店铺名称" align="center" />
          <el-table-column label="绑定团队" align="center" width="260">
            <template #default="scope">
              <div v-for="item in tableDataB" :key="item.id">
                <el-text v-if="scope.row.userId == item.id" class="mx-1">{{ item.name }}</el-text>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="开启留存" align="center">
            <template #default="scope">
              <el-switch
                v-model="scope.row.offs"
                :active-value="1"
                :inactive-value="0"
                @click="handleStatusChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button
                type="primary"
                text
                bg
                size="small"
                @click="settingIdApi(scope.row)"
                :disabled="scope.row.name === '超级管理员'"
                >修改</el-button
              >
              <el-button
                type="danger"
                text
                bg
                size="small"
                @click="handleDelete(scope.row)"
                :disabled="scope.row.name === '超级管理员'"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 弹出框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="settingId == false ? '添加信息' : '修改信息'"
      width="30%"
      @closed="resetForm"
    >
      <el-form ref="formRef" :model="formData.data" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item label="绑定团队" prop="userId">
          <el-select v-model="formData.data.userId" filterable clearable style="width: 240px">
            <el-option v-for="item in tableDataB" :key="item.id" :label="item.name" :value="item.id"
          /></el-select>
        </el-form-item>
        <el-form-item prop="shopId" label="店铺id">
          <el-input v-model="formData.data.shopId" placeholder="请输入店铺ID" style="width: 100%" />
        </el-form-item>
        <el-form-item prop="shopName" label="店铺名字">
          <el-input v-model="formData.data.shopName" placeholder="请输入店铺名字" style="width: 100%" />
        </el-form-item>
        <el-form-item prop="index" label="店铺平台">
          <!-- <el-input
            v-model="formData.data.index"
            placeholder="云邮平台输入0，火影平台输入1,河南电信抖店输入2"
            style="width: 100%"
          /> -->
          <el-select v-model="formData.data.index" filterable clearable style="width: 240px">
            <el-option v-for="item in shopIds" :key="item.id" :label="item.name" :value="item.id"
          /></el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}
.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
.table-wrapper {
  margin-bottom: 20px;
}
.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
